package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.*;
import com.itheima.service.mongo.VoiceService;
import com.itheima.util.ConstantUtil;
import javafx.beans.binding.When;
import jdk.nashorn.internal.objects.annotations.Where;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@DubboService
public class VoiceServiceImpl implements VoiceService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;//全局id自增器

    @Override
    public void sendVoice(Voice voice) {
        //给voice设置vid
        if (null==voice.getVid()) {
            voice.setVid(redisIdService.getNextId("voice"));
        }
        mongoTemplate.save(voice);
    }

    @Override
    public List<Voice> receiveVoice() {
        Query query = new Query(Criteria.where("received").is(false)).with(Sort.by(Sort.Order.desc("created")));
        // Voice voice = mongoTemplate.findOne(query, Voice.class);
        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);
        // if (null==voice){
        //     voice=new Voice();
        // }
        return voiceList;
    }

    @Override
    public UserTimes findTimesById(Long useId) {
        UserTimes userTimes = mongoTemplate.findOne(new Query(Criteria.where("userId").is(useId)), UserTimes.class);
        if (null==userTimes) {
            userTimes=new UserTimes();
            userTimes.setUserId(useId);
            userTimes.setCreated(new Date());
        }
        //第二天次数更新为10次
        Date created = userTimes.getCreated();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String oldDate = format.format(created);
        String newDate = format.format(new Date());
        if (!oldDate.equals(newDate)) {
            userTimes.setTimes(10);
            userTimes.setCreated(new Date());
        }
        userTimes.setTimes(userTimes.getTimes()-1);
        mongoTemplate.save(userTimes);
        return userTimes;
    }
}
